<template>
  <el-card>
    <el-col :span="12">
      <p>
        别称用于区分公司，账号需带上别称登录（如别称名为techns,登录账号为SSR123@techns）。
      </p>
      <el-form ref="form"
               :model="form"
               :rules="rules"
               label-width="100px"
               class="demo-ruleForm">
        <el-form-item label="公司别称"
                      prop="name">
          <el-input v-model="form.name"></el-input>
          <span>别称只能为纯英文，5-20个字符</span>
        </el-form-item>
        <el-form-item>
          <el-button type="primary"
                     :loading="loading"
                     @click="onSubmit">确 定</el-button>
        </el-form-item>
      </el-form>
    </el-col>
  </el-card>
</template>
<script>
import { tenant } from "@/api/index";
import { mapState } from "vuex";
export default {
  name: "CompanyNickName",
  data () {
    return {
      rules: {
        name: [
          { required: true, message: "公司别称不能为空", trigger: "change" },
          { pattern: /^[A-Za-z]+$/g, message: "请输入正确的公司别称" },
          { min: 5, max: 20, message: "请输入正确的公司别称", trigger: "blur" }
        ]
      },
      loading: false,
      form: {
        name: ""
      },
      userInfo: sessionStorage.getItem('userInfo')
    };
  },
  computed: {
    user () {
      return JSON.parse(this.userInfo)
    },
    tenantAlias () {
      return this.user?.tenantAlias
    }
  },
  created () {
    this.form.name = this.tenantAlias;
  },
  methods: {
    async onSubmit () {
      this.$refs.form.validate((valid) => {
        if (valid) {
          this.loading = true;
          this.$confirm("修改后需要重新登录，确定修改吗？", "提示", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning"
          })
            .then(() => {
              this.update();
            })
            .catch(() => {
              this.loading = false;
            });
        }
      });
    },
    async update () {
      let { code, message } = await tenant.updateNickName(this.form.name);
      this.$message[code === 0 ? "success" : "error"](message);
      this.loading = false;
      if (code === 0) {
        this.$router.push({ name: "login" });
      }
    }
  }
};
</script>
